import axios from "axios";
import { MessageBox, Message, Loading } from "element-ui";
import resetMessage from '@/utils/resetMessage';
import store from "@/store";
import { getToken } from "@/utils/auth";
let loading;
function startLoading() {
  //使用Element loading-start 方法
  loading = Loading.service({
    lock: true,
    background: "rgba(255, 255, 255, 0.1)",
    text: "加载中...",
  });
}
function endLoading() {
  //使用Element loading-close 方法
  loading.close();
}
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 2000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    startLoading();
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers.token = getToken();
      // config.headers["X-Token"] = getToken();
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    endLoading();
    const res = response.data;
    let code = res.code * 1;
    let msg = res.msg
    if (!code) {
      return res;
    } else if (code !== 0) {
      if (msg == 'token失效' || code == 0x00010003 || code == 0x00010004) {
        MessageBox.alert('登录超时,请重新登录！', '验证Token失败', {
          confirmButtonText: '确定',
          callback: () => {
            //跳转登录页   callback点击确定按钮后的回调函数
            store.dispatch('user/logout').then(() => {
              location.reload(true)
            })
          }
        });
      }
      resetMessage({
        message: res.msg || "Error",
        type: "error",
        duration: 5 * 1000,
      });
      console.log(res.msg);
      return;
    } else {
      return res;
    }
  },
  (error) => {
    endLoading();
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
